<?php

namespace App\Tasks;

use App\Clients\YikaCar\YikaBike;
use App\Models\MallDateFinance;
use Exception;
use GuzzleHttp\Exception\GuzzleException;

class YikaSyncDatasTask  extends MeiTuanMallTask
{
    /**
     * @throws GuzzleException
     * @throws Exception
     */
    public function execute(): void
    {
        $startDate = $this->maxDate(4);
        $diffDate = (strtotime(date("Y-m-d",time())) - strtotime(date("Y-m-d",strtotime($startDate)))) / 86400;
        $groupData = json_decode($this->mall->counts_datas,true);
        $accounts = [];
        foreach ($groupData as $plat=>$data){
            $account = $this->account->account->accountSub->where("plamt",$plat)->first();
            $accounts[$plat] = $account;
        }
        $queryDates = [];
        foreach (range(0,$diffDate,1) as $index=>$item){
            $temp = [
                "udate"=>date("Y-m-d",strtotime($startDate) + 1 * $index * 86400)
            ];
            foreach ($groupData as $plat=>$data){
                $beginDate = date("Y-m-d H:i:s",strtotime($startDate) + 1 * $index * 86400);
                $endDate = date("Y-m-d H:i:s",strtotime($beginDate) + 86399);
                $temp[$plat]["income"] = [
                    "stime"=>$beginDate,
                    "etime"=>$endDate
                ];
            }
            $queryDates[] = $temp;
        }
        foreach ($queryDates as $queryDate){
            $udate = $queryDate["udate"];
            var_dump($udate);
            unset($queryDate["udate"]);
            $model = MallDateFinance::query()
                ->where("merchant_no",$this->mall->merchant_no)
                ->where("date",$udate)
                ->first();
            if(!empty($model) && $model->is_update == 1){
                continue;
            }
            $income = 0;
            $subaoumt = 0;
            foreach ($queryDate as $plat=>$data){
                $account = $accounts[$plat];
                $incomeClient = new YikaBike($account);
                $response = $incomeClient->loopExecute($data["income"])->contents();
                $income += $response["income"];
                $subaoumt += $response["income"] * 0.15;
            }
            $income = round($income,2);
            $subaoumt = round($subaoumt,2);
            empty($model) and $model = new MallDateFinance;
            $model->bill_no = $udate;
            $model->merchant_no = $this->mall->merchant_no;
            $model->date = $udate;
            $model->income = $income;
            $model->settle_money = $subaoumt;
            $model->save();
        }
    }
}
